package com.zz.admin.auth.extension;

import com.alibaba.fastjson.JSON;
import com.zz.common.base.dto.ResultDto;
import com.zz.common.constants.ApiConstants;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import java.io.IOException;

/**
 * 当用户未经过认证访问受保护资源时出发
 *
 * @author zl
 * @version 1.0
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        ResultDto resultDto = new ResultDto(ApiConstants.RESULT_FAIL, authException.getMessage());
        String json = JSON.toJSONString(resultDto);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.setStatus(ApiConstants.FORBIDDEN);
        response.getWriter().print(json);
    }
}
